package com.fiveGroup.controller;

import cn.hutool.core.util.RandomUtil;
import com.fiveGroup.pojo.vo.DataVo;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

/*
    验证码
    1.先获取一个验证码
    2.验证码与用户信息一并发到登录请求中
    3.验证码验证  不通过
 */
@RestController
@RequestMapping("/api/captcha")
@Slf4j
public class CaptchaController {

    //验证码有效期
    private static final long CODE_EXPIRE_TIME = 300;
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //邮箱获取验证码
    @PostMapping("/emailCode")
    public DataVo getEmailCode(@RequestParam
                               @Valid
                               @Email(message = "邮件格式不正确") String email) {
        //验证码生成6位数字字符串  hutool包
        String code = RandomUtil.randomString(6);
        log.info(username);
        //存储验证码到Redis,设置为1分钟过期时间
        String redisKey = "email:code:" + email;
        redisTemplate.opsForValue().set(redisKey, code, Duration.ofSeconds(CODE_EXPIRE_TIME));
        //验证码标题
        String subject = "【欢迎注册二手交易平台】验证码";
        //验证码的内容格式与具体内容
        String content = "您的验证码为：" + code + "有效期为5分钟，请勿泄露验证码";
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            //邮件的发送人
            helper.setFrom(username);
            //邮件接收人
            helper.setTo(email);
            //设置邮件标题与内容
            helper.setSubject(subject);
            helper.setText(content);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("验证码发送失败:{}", e.getMessage());
            return DataVo.fail("验证码发送失败");
        }
        return DataVo.success(email);
    }

    //验证验证码接口
    @PostMapping("/verifyCode")
    public DataVo verifyCode(@RequestParam String email,
                             @RequestParam String code) {
        String redisKey = "email:code:" + email;
        String storedCode = redisTemplate.opsForValue().get(redisKey);

        if (storedCode == null) {
            return DataVo.fail("验证码已过期,请重新获取");
        }
        if (!storedCode.contains(code)) {
            return DataVo.fail("验证码错误");
        }
        //验证成功后删除验证码，防止重复使用
        redisTemplate.delete(redisKey);
        return DataVo.success("验证成功");
    }
}
